/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.purpose.bean.ResponsibilitiesLibBean;
import com.koron.purpose.mapper.ResponsibilitiesLibMapper;
import com.koron.purpose.service.api.ResponsibilitiesLibService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.system.domain.DictData;
import com.koron.system.service.api.DictDataService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.util.*;

@SuppressWarnings("deprecation")
@Service
public class ResponsibilitiesLibServiceImpl implements ResponsibilitiesLibService {

    private final static Logger logger= LoggerFactory.getLogger(ResponsibilitiesLibServiceImpl.class);
    // 状态(0-废弃 1-正常)
    private final String STATUS_0 = "0";
    // 状态(0-废弃 1-正常)
    private final String STATUS_1 = "1";

    @Autowired
    private DictDataService dataService;

    @Override
    public MessageBean queryForList(String item,String keyword, String corpCode, String status, Integer page, Integer pageSize) {
        MessageBean<DataBean<ResponsibilitiesLibBean>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            ResponsibilitiesLibMapper mapper = factory.getMapper(ResponsibilitiesLibMapper.class);
            // 查询
            Map map = new HashMap();
            map.put("item", item);
            map.put("corpCode", corpCode);
            if (!StringUtils.isEmpty(status)) {
                map.put("status", status);
            }
            if(!StringUtils.isEmpty(keyword)){
                map.put("keyword", keyword);
            }
            if (page != null && pageSize != null) {
                page = (page == null || page < 1) ? 1 : page;
                pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
                int pageStart = (page - 1) * pageSize;
                map.put("pageStart", pageStart);
                map.put("pageSize", pageSize);
            }
            List<ResponsibilitiesLibBean> list = mapper.queryForList(map);
            DataBean<ResponsibilitiesLibBean> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(pageSize);
            dataBean.setPageNo(page);
            if (page != null || pageSize != null) {
                // 总条数
                Integer totalNumber = mapper.countForList(map);
                int num = totalNumber / pageSize;
                // 总页数
                Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
                dataBean.setTotalNumber(totalNumber);
                dataBean.setTotalPage(totalPage);
            }
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean queryById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            ResponsibilitiesLibMapper mapper = factory.getMapper(ResponsibilitiesLibMapper.class);
            ResponsibilitiesLibBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("未查到该职责项");
            }
            msg.setData(bean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean deleteById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            ResponsibilitiesLibMapper mapper = factory.getMapper(ResponsibilitiesLibMapper.class);
            ResponsibilitiesLibBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("没有获取到该职责项");
                factory.close(false);
                return msg;
            }
            int i = mapper.delete(id, STATUS_0);
            if (i != 1) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("停用失败!");
                factory.close(false);
            } else {
                factory.close();
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }finally {
            factory.close();
        }
        return msg;
    }

    @Override
    public MessageBean start(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            ResponsibilitiesLibMapper mapper = factory.getMapper(ResponsibilitiesLibMapper.class);
            ResponsibilitiesLibBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("没有获取到该职责项");
                factory.close(false);
                return msg;
            }
            int i = mapper.delete(id, STATUS_1);
            if (i != 1) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("启用失败!");
                factory.close(false);
            } else {
                factory.close();
            }
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }finally {
            factory.close();
        }
        return msg;
    }

    @Override
    public MessageBean insert(StaffBean user, ResponsibilitiesLibBean bean) {
        bean.setStatus(STATUS_1);
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(bean.getItem()) || StringUtils.isEmpty(bean.getStatus()) || bean.getOrderNo() == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            ResponsibilitiesLibMapper mapper = factory.getMapper(ResponsibilitiesLibMapper.class);
            Date date = new Date();
            bean.setAddTime(date);
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(date);
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            mapper.insert(bean);
            msg.setData(bean.getId());
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean update(StaffBean user, ResponsibilitiesLibBean bean) {
        bean.setStatus(STATUS_1);
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        SessionFactory factory = new SessionFactory();
        try {
            ResponsibilitiesLibMapper mapper = factory.getMapper(ResponsibilitiesLibMapper.class);
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            if (mapper.update(bean) != 1) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("修改失败");
                factory.close(false);
            }
            msg.setData(bean.getId());
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    public MessageBean<String> importExcel(StaffBean user, MultipartFile file){
        MessageBean<String> msg=MessageBean.create(BusinessCode.SUCCESS.getCode(),BusinessCode.SUCCESS.getDescription(),String.class);
        try(SessionFactory factory=new SessionFactory()){
            if (file==null){
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription("未上传文件");
                return msg;
            }
            InputStream inputStream=file.getInputStream();
            XSSFWorkbook workbook=new XSSFWorkbook(inputStream);
            if (null==workbook){
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription("上传文件为空");
                return msg;
            }
            XSSFSheet sheet=workbook.getSheetAt(0);
            if (null==sheet){
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription("上传文件为空");
                return msg;
            }
            int rowsNumber=sheet.getPhysicalNumberOfRows();
            List<ResponsibilitiesLibBean> responsibilitiesLibBeans=new ArrayList<>();
            StringBuilder description=new StringBuilder();
            Date date=new Date();
            for(int i=1;i<rowsNumber;i++){
                XSSFRow row=sheet.getRow(i);
                if(row == null){
                    continue;
                }
                String indexValue=getCellValue(row.getCell(0));
                String item=getCellValue(row.getCell(1));
                String keyWord=getCellValue(row.getCell(2));
                String corpName=getCellValue(row.getCell(3));
                DictData data=dataService.matchDictData("公司",corpName);
                if (data==null){
                    description.append("第"+i+"行公司名称不对，无法导入，请输入完整的公司名称");
                    continue;
                }
                ResponsibilitiesLibBean bean=new ResponsibilitiesLibBean();
                if(StringUtils.isNotEmpty(indexValue)){
                    bean.setOrderNo((int)Double.parseDouble(indexValue));
                }else{
                    bean.setOrderNo(i);
                }
                bean.setItem(item);
                bean.setKeyword(keyWord);
                bean.setCorpCode(data.getDictValue());
                bean.setCorpName(corpName);
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                bean.setAddTime(date);
                bean.setAddUser(user.getCode());
                bean.setAddUserName(user.getName());
                bean.setUpdateTime(date);
                bean.setUpdateUser(user.getCode());
                bean.setUpdateUserName(user.getName());
                bean.setStatus(STATUS_1);
                responsibilitiesLibBeans.add(bean);
            }
            if(null!=responsibilitiesLibBeans&&responsibilitiesLibBeans.size()>0){
                factory.getMapper(ResponsibilitiesLibMapper.class).batchInsert(responsibilitiesLibBeans);
                if (StringUtils.isNotEmpty(description))
                    msg.setDescription(description.toString());
                return msg;
            }
            return msg;
        }catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    /**
     * 获取单元格的值
     * @param cell
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getCellValue(XSSFCell cell) {
        if (cell == null)
            return "";
        if (cell.getCellTypeEnum() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellTypeEnum() == CellType.FORMULA) {
            return cell.getCellFormula();
        } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return "";
        }
    }
}
